<?php


namespace app\admin\controller\Course;


use app\admin\controller\BaseController;
use app\admin\model\Course\CourseCateRelationModel;
use app\admin\model\Course\CourseModel;
use app\Utils\ImageUtil;
use app\Utils\Util;
use Exception;
use think\facade\Db;
use think\Request;

class Course extends BaseController
{

    /**
     * 分页查询
     * @param Request $request
     * @return array
     */
    public function getCourseList(Request $request)
    {
        $page = (int)$request->param('page', 1);
        $limit = (int)$request->param('limit', 10);
        $title = $request->param('title');
        $is_group = $request->param('is_group', 0);
        $is_del = $request->param('is_del');
        $is_show = $request->param('is_show');
        $phone = $request->param('phone');
        $arr = CourseModel::getCourseListWhere($title, $is_group, $is_del, $is_show, $phone,$page, $limit);
        $list = $arr['data'];
        $count = $arr['count'];
        foreach ($list as &$item) {
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
            $images = !empty($item['slider_img']) ? json_decode($item['slider_img'], true) : [];
            foreach ($images as &$image) {
                $image = ImageUtil::i()->replaceUrl($image);
            }
//            $item['time'] = $item['start_time'] .'-'.$item['end_time'];
            $item['slider_img'] = $images;
            $item['details'] = !empty($item['details']) ? htmlspecialchars_decode($item['details']) : "";
        }
        return Util::returnPageJson(self::CODE_DATA, $count, $list, "");
    }


    /**
     * 添加
     * @param Request $request
     * @return array
     */
    public function addCourse(Request $request)
    {
        $param = $request->param();

        $data = [
            'title' => !empty($param['title']) ? $param['title'] : "",
            'teacher_brief' => !empty($param['teacher_brief']) ? $param['teacher_brief'] : "",
            'brief' => !empty($param['brief']) ? $param['brief'] : "",
            'price' => !empty($param['price']) ? $param['price'] : 0,
            'cost_price' => !empty($param['cost_price']) ? $param['cost_price'] : 0,
            'vip_price' => !empty($param['vip_price']) ? $param['vip_price'] : 0,
            'group_price' => !empty($param['group_price']) ? $param['group_price'] : 0,
            'group_num' => !empty($param['group_num']) ? $param['group_num'] : 0,
            'is_group' => !empty($param['is_group']) ? 1 : 0,
            'sort' => !empty($param['sort']) ? $param['sort'] : 0,
            'details' => !empty($param['details']) ? htmlspecialchars($param['details']) : "",
            'school_id' => !empty($param['school_id']) ? $param['school_id'] : 0,
            'up_time' => date("Y-m-d H:i:s", time()),
            'add_time' => date("Y-m-d H:i:s", time()),
            'deposit' => !empty($param['deposit']) ? htmlspecialchars($param['deposit']) : 0,
            'brief_group' => !empty($param['brief_group']) ? htmlspecialchars($param['brief_group']) : '',
        ];

        //图片上传(单图)
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "course/product/img/";
            $url = ImageUtil::i()->upload($file, $path);
        }
        //多图
        if (!empty($request->file('files'))) {
            $files = $request->file('files');
            $path = "course/product/slider_img/";
            $urls = ImageUtil::i()->upload($files, $path);
        }
        if (!empty($param['start_time'])) {
            $save['start_time'] = $param['start_time'];
        }
        if (!empty($param['end_time'])) {
            $save['end_time'] = $param['end_time'];
        }
//        if (!empty($param['time'])) {
//            $time = explode('-', $param['time']);
//            $save['start_time'] = $time[0];
//            $save['end_time'] = $time[1];
//        }
        if (!empty($url)) {
            $data['img'] = $url;
        }
        if (!empty($urls)) {
            $data['slider_img'] = json_encode($urls);
        }

        if (!empty($param['is_show']) && $param['is_show'] == "on") {
            $data['is_show'] = 1;
        }
        if (!empty($param['is_del']) && $param['is_del'] == "on") {
            $data['is_del'] = 1;
        }

        Db::startTrans();
        try {
            $id = CourseModel::addCourse($data);
            if ($id) {
                if (!empty($param['select'])) {
                    $cate_ids = explode(',', $param['select']);
                    $data = [];
                    foreach ($cate_ids as $cate_id) {
                        $arr['course_id'] = $id;
                        $arr['cate_id'] = $cate_id;
                        $arr['add_time'] = date("Y-m-d H:i:s", time());
                        array_push($data, $arr);
                    }
                    $flag = CourseCateRelationModel::addCourseCateRelation($data);
                    if ($flag) {
                        DB::commit();
                        return Util::returnJson(self::CODE_SUCCESS, null, "添加成功");
                    } else {
                        DB::rollBack();
                        return Util::returnJson(self::CODE_ERROR, null, "添加失败3");
                    }
                } else {
                    DB::commit();
                    return Util::returnJson(self::CODE_SUCCESS, $id, "添加成功");
                }
            } else {
                DB::rollBack();
                return Util::returnJson(self::CODE_ERROR, null, "添加失败2");
            }
        } catch (Exception $e) {
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, null, "添加失败1");
        }
    }

    /**
     * 更新
     * @param Request $request
     * @return array
     */
    public function editCourse(Request $request)
    {
        $param = $request->param();

        $save = [
            'title' => !empty($param['title']) ? $param['title'] : "",
            'teacher_brief' => !empty($param['teacher_brief']) ? $param['teacher_brief'] : "",
            'brief' => !empty($param['brief']) ? $param['brief'] : "",
            'price' => !empty($param['price']) ? $param['price'] : 0,
            'cost_price' => !empty($param['cost_price']) ? $param['cost_price'] : 0,
            'vip_price' => !empty($param['vip_price']) ? $param['vip_price'] : 0,
            'group_price' => !empty($param['group_price']) ? $param['group_price'] : 0,
            'group_num' => !empty($param['group_num']) ? $param['group_num'] : 0,
            'is_group' => !empty($param['is_group']) ? 1 : 0,
            'sort' => !empty($param['sort']) ? $param['sort'] : 0,
            'details' => !empty($param['details']) ? htmlspecialchars($param['details']) : "",
            'school_id' => !empty($param['school_id']) ? $param['school_id'] : 0,
            'up_time' => date("Y-m-d H:i:s", time()),
            'deposit' => !empty($param['deposit']) ? htmlspecialchars($param['deposit']) : 0,
            'brief_group' => !empty($param['brief_group']) ? htmlspecialchars($param['brief_group']) : '',
        ];

        //图片上传(单图)
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "course/product/img/";
            $url = ImageUtil::i()->upload($file, $path);
        }
        //多图
        if (!empty($request->file('files'))) {
            $files = $request->file('files');
            $path = "course/product/slider_img/";
            $urls = ImageUtil::i()->upload($files, $path);
        }
        if (!empty($param['start_time'])) {
            $save['start_time'] = $param['start_time'];
        }
        if (!empty($param['end_time'])) {
            $save['end_time'] = $param['end_time'];
        }
//        if (!empty($param['time'])) {
//            $time = explode('-', $param['time']);
//            $save['start_time'] = $time[0];
//            $save['end_time'] = $time[1];
//        }
        if (!empty($url)) {
            $save['img'] = $url;
        }
        if (!empty($urls)) {
            $save['slider_img'] = json_encode($urls);
        }

        if (!empty($param['is_show']) && $param['is_show'] == "on") {
            $save['is_show'] = 1;
        }
        if (!empty($param['is_del']) && $param['is_del'] == "on") {
            $save['is_del'] = 1;
        }


        DB::startTrans();
        try {
            CourseModel::updateCourseWhere([['id', '=', $param['id']]], $save);
            if (!empty($param['select'])) {
                //清除
                CourseCateRelationModel::delCourseCateRelationWhere([['course_id', '=', $param['id']]]);
                $cate_ids = explode(',', $param['select']);
                $data = [];
                foreach ($cate_ids as $cate_id) {
                    $arr['course_id'] = $param['id'];
                    $arr['cate_id'] = $cate_id;
                    $arr['add_time'] = date("Y-m-d H:i:s", time());
                    array_push($data, $arr);
                }
                $flag = CourseCateRelationModel::addCourseCateRelation($data);
                if ($flag) {
                    DB::commit();
                    return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
                } else {
                    DB::rollBack();
                    return Util::returnJson(self::CODE_ERROR, null, "修改失败1");
                }
            } else {
                DB::commit();
                return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
            }
        } catch (Exception $e) {
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, null, "修改失败2");
        }
    }

    /**
     * 修改类型
     * @param Request $request
     * @return array
     */
    public function editCourseType(Request $request)
    {
        $param = $request->post();
        if (!empty($param['is_show'])) {
            if ($param['is_show'] == "on") {
                $save['is_show'] = 1;
            } else {
                $save['is_show'] = 0;
            }
        }
        if (!empty($param['is_del'])) {
            if ($param['is_del'] == "on") {
                $save['is_del'] = 1;
            } else {
                $save['is_del'] = 0;
            }
        }

        $flag = CourseModel::updateCourseWhere([['id', '=', $param['id']]], $save);
        if ($flag) {
            return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "修改失败1");
        }
    }
}
